package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConst;
import com.itheima.constant.RedisConst;
import com.itheima.entity.Result;
import com.itheima.pojo.Order;
import com.itheima.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * @author ：daqiang
 * @date ：Created in 2019/11/25
 * @description ：
 * @version: 1.0
 */

@RestController
@RequestMapping("/order")
public class OrderController {

    @Reference
    OrderService orderService;

    @Autowired
    JedisPool jedisPool;

    /**
     * 步骤：
     *  1.校验验证码
     *  2.设置预约类型
     *  3.添加预约信息到数据库
     *  4.发送短信给客户
     *
     * @param map
     * @return
     */
    @RequestMapping("/submit")
    public Result submit(@RequestBody Map<String,String> map){
        //获取手机号码
        String telephone = map.get("telephone");
        //获取Redis中的验证码
        String validateCodeInRedis = jedisPool.getResource().get(RedisConst.SENDTYPE_ORDER + "-" + telephone);
        //获取参数中的验证码
        String validateCodeInParam = map.get("validateCode");
        //1.校验验证码
        if (!(validateCodeInRedis != null && validateCodeInRedis.equals(validateCodeInParam))){
            return new Result(false, MessageConst.VALIDATECODE_ERROR);
        }
        //2.设置预约类型
        map.put("orderType", Order.ORDERTYPE_WEIXIN);
        //3.添加预约信息到数据库
        Result result = null;
        try {
            result = orderService.addOrder(map);
        } catch (ParseException e) {
            e.printStackTrace();
            System.out.println("日期处理失败");
        }
        //4.发送短信给客户
        if (result.isFlag()){
            //省略
        }
        return result;
    }

    @RequestMapping("/findById")
    public Result findById(Integer id){
        try {
            Map<String,Object> resultMap = orderService.findById(id);
            Date orderDate = (Date) resultMap.get("orderDate");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String orderDateStr = sdf.format(orderDate);
            resultMap.put("orderDate",orderDateStr);
            return new Result(true,MessageConst.QUERY_ORDER_SUCCESS,resultMap);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConst.QUERY_ORDER_FAIL);
        }
    }
}
